import os
from utils import doc_util, read_config as config, json_util, date_util
from service import score_service, data_service, users_service
from webs.service import common_service, config_service

users_path = os.path.join(config.data_path, 'common', 'users')

colors = [
    'progress-bar progress-bar-danger',
    'progress-bar progress-bar-warning',
    'progress-bar progress-bar-primary',
    'progress-bar progress-bar-success',
]


# 获取用户监控股票信息
def get_user_monitor(params):
    monitor_list = users_service.get_all_monitor(params[config_service.username])[params[config_service.username]]
    title_list = ['序号', '名称', '编码', '操作']
    data_dict = {}
    count = 0
    for monitor_info in monitor_list:
        count += 1
        name = monitor_info['name']
        code = monitor_info['code']
        data_dict[count] = {}
        data_dict[count]['名称'] = name
        data_dict[count]['编码'] = code
        data_dict[count]['操作'] = {'name': '删除', 'url': config_service.url13}
    return get_board('监控信息', title_list, data_dict)


# 所有股票信息
def get_all_stock():
    stock_dict = data_service.new_stock_all()
    title_list = ['序号', '名称', '编码', '操作']
    data_dict = {}
    count = 0
    for code in stock_dict.keys():
        count += 1
        name = stock_dict[code]['name']
        data_dict[count] = {}
        data_dict[count]['名称'] = name
        data_dict[count]['编码'] = code
        data_dict[count]['操作'] = {'name': '添加', 'url': config_service.url12}
    return get_board('所有股票信息', title_list, data_dict)


# 获取当日触发情况
# flag 1:查询当前触发 2:查询全部触发
def get_board(title, title_list, data_dict):
    a = b'<div class="row">'
    a += b'    <div class="col-md-12">'
    a += b'        <div class="white-box">'
    a += bytes('<h2 class="header-title"> ' + title + ' </h2>', encoding='utf-8')
    a += b'            <div class="table-responsive">'
    a += b'                <table class="table table-hover">'
    a += b'                    <thead>'
    a += b'                    <tr>'
    for tit in title_list:
        a += bytes('<th>' + tit + '</th>', encoding='utf-8')
    a += b'                    </tr>'
    a += b'                    </thead>'
    a += b'                    <tbody>'

    for row_num in data_dict.keys():
        a += b'<tr>'
        a += bytes('<td>' + str(row_num) + '</td>', encoding='utf-8')
        row_info = data_dict[row_num]
        for cell_title in row_info.keys():
            if cell_title == '评分':
                score = row_info[cell_title]
                a += b'<td>'
                a += b'    <div class="progress progress-striped progress-sm">'
                a += bytes('<div class="' + colors[score % 4] + '" style="width: ' + str(score) + '%;"></div>',
                           encoding='utf-8')
                a += b'    </div>'
                a += b'</td>'
            elif cell_title == '操作':
                config = row_info[cell_title]
                name = config['name']
                if name == '添加':
                    a += b'<td>'
                    a += bytes('<form action="' + config['url'] + ' " method="post" name = "add" >',
                               encoding='utf-8')
                    a += bytes('<input type="hidden" name ="stockCode" value="' + row_info['编码'] + '" >',
                               encoding='utf-8')
                    a += bytes('<input type="submit" value="' + name + '" class="btn btn-success"  >',
                               encoding='utf-8')
                    a += b'</form>'
                    a += b'</td>'
                elif name == '删除':
                    a += b'<td>'
                    a += bytes('<form action="' + config['url'] + ' " method="post" name = "add" >',
                               encoding='utf-8')
                    a += bytes('<input type="hidden" name ="stockCode" value="' + row_info['编码'] + '" >',
                               encoding='utf-8')
                    a += bytes('<input type="submit" value="' + name + '" class="btn btn-danger outline-btn round" >',
                               encoding='utf-8')
                    a += b'</form>'
                    a += b'</td>'
            else:
                a += bytes('<td>' + row_info[cell_title] + '</td>', encoding='utf-8')
        a += b'</tr>'
    a += b'                    <tr>'
    a += b'                    </tbody>'
    a += b'                </table>'
    a += b'            </div>'
    a += b'        </div>'
    a += b'    </div>'
    a += b'</div>'
    return a


def get_all_monitor():
    path = os.path.join(config.data_path, 'task', 'document', '突破均线', 'stock_monitor_dict')
    monitor_dict = doc_util.get_a_doc_dict(path, 'code')
    up_flag = 0
    # user_m_dict = monitor_dict
    # if user_code != '':
    #     if os.path.exists(os.path.join(users_path, user_code)):
    #         user_m_dict = doc_util.get_a_doc_dict(os.path.join(users_path, user_code), 'code')
    result_list = [['序号', '名称', '触发时间', '触发类型', '等级', '评分', '操作']]
    for code in monitor_dict.keys():
        # if code not in user_m_dict.keys():
        #     continue
        monitor_info = json_util.info_to_json(monitor_dict[code])
        code = monitor_info['code']
        name = monitor_info['name']
        result_file_path = monitor_info['result_file_path']
        if 'score_info' not in monitor_info:
            up_flag = 1
        else:
            score_info = monitor_info['score_info']
            if 'exam_time' in score_info.keys():
                exam_time = score_info['exam_time']
                if (date_util.get_timestamp_now() - exam_time) > 600:
                    up_flag = 1
            else:
                up_flag = 1
        if up_flag == 1:
            monitor_info = score_service.common_exam(monitor_info)
            monitor_dict[code] = monitor_info
        score_info = json_util.info_to_json(monitor_info['score_info'])
        if 'trigger_time' not in monitor_info.keys():
            monitor_info['trigger_time'] = '2000-01-01 00:00:00'
            monitor_info['trigger_timestamp'] = date_util.datetime2timestamp('2000-01-01 00:00:00')
        level = score_info['level']
        score = score_info['score']
        trigger_time = monitor_info['trigger_time']  # 触发时间
        file_list = []
        file_list.append(name)
        file_list.append(trigger_time[0:10])
        file_list.append(result_file_path)
        file_list.append(level)
        file_list.append(score)
        file_list.append(code)
        result_list.append(file_list)
    if up_flag:
        doc_util.gen_a_doc(os.path.join(config.data_path, 'task', 'document', '突破均线'),
                           'stock_monitor_dict',
                           monitor_dict)
    return get_monitor_board(result_list, '全部监控股票')


# 获取当日触发情况
# flag 1:查询当前触发 2:查询全部触发
def get_monitor_board(result_list, title):
    a = b'<div class="row">'
    a += b'    <div class="col-md-12">'
    a += b'        <div class="white-box">'
    a += bytes('<h2 class="header-title"> ' + title + ' </h2>', encoding='utf-8')
    a += b'            <div class="table-responsive">'
    a += b'                <table class="table table-hover">'
    a += b'                    <thead>'
    a += b'                    <tr>'
    for title in result_list[0]:
        a += bytes('<th>' + title + '</th>', encoding='utf-8')
    a += b'                    </tr>'
    a += b'                    </thead>'
    a += b'                    <tbody>'
    for i in range(1, len(result_list)):
        a += b'<tr>'
        a += bytes('<td>' + str(i) + '</td>', encoding='utf-8')
        td_list = result_list[i]
        for i in range(len(td_list)):
            if i == 4:
                score = td_list[i]
                a += b'<td>'
                a += b'    <div class="progress progress-striped progress-sm">'
                a += bytes('<div class="' + colors[score % 4] + '" style="width: ' + str(score) + '%;"></div>',
                           encoding='utf-8')
                a += b'    </div>'
                a += b'</td>'
            elif i == 5:
                a += b'<td>'
                a += b'<form>'
                a += bytes('<input type="hidden" class="form-control" value="' + td_list[i] + '" >', encoding='utf-8')
                a += bytes('<input type="submit" value="' + '删除' + '" class="btn btn-danger outline-btn round" >',
                           encoding='utf-8')
                a += b'</form>'
                a += b'</td>'
            else:
                a += bytes('<td>' + td_list[i] + '</td>', encoding='utf-8')
        a += b'</tr>'
    a += b'                    <tr>'
    a += b'                    </tbody>'
    a += b'                </table>'
    a += b'            </div>'
    a += b'        </div>'
    a += b'    </div>'
    a += b'</div>'
    return a


if __name__ == '__main__':
    get_all_stock()
